package com.hedl.practice.diyJava.reflex.field_access;

import com.hedl.testClass.Person;

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) {

        //访问
        /*Object p = new Person("Xiao ming");

        Class cls = p.getClass();       //class实例
        try {
            Field f = cls.getDeclaredField("name");     //field实例
            f.setAccessible(true);      //因为是私有权限，所以需要开锁
            Object value = f.get(p);        //获取字段值
            System.out.println(value);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }*/

        //设置值
        /*Person p = new Person("Xiao Ming");
        System.out.println(p.getName());

        Class c = p.getClass();
        try {
            Field f = c.getDeclaredField("name");
            f.setAccessible(true);
            f.set(p,"Xiao Hong");
            System.out.println(p.getName());

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }*/

        //练习
        String name = "Xiao ming";
        int age = 20;

        Person p = new Person();

        //String[] s = {"name","age"};
        Class c = p.getClass();

        //方法一
        /*Field[] fs = c.getDeclaredFields();
        for (Field f:fs){
            f.setAccessible(true);
            if (f.getName() == "name"){
                try {
                    f.set(p,name);
                    System.out.println(f.getName()+":"+p.getName());
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }else if (f.getName() == "age"){
                try {
                    f.set(p,age);
                    System.out.println(f.getName()+":"+p.getAge());
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }*/


        //方法二
        try {
            Field f = c.getDeclaredField("name");
            Field f1 = c.getDeclaredField("age");

            f.setAccessible(true);
            f1.setAccessible(true);

            f.set(p,name);
            f1.set(p,age);

            System.out.println(p.getName());
            System.out.println(p.getAge());
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }
}